package com.juku2024.juku.fragment

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.recyclerview.widget.RecyclerView
import com.juku2024.juku.DownloadDetailActivity
import com.juku2024.juku.R
import com.juku2024.juku.SettingActivity
import com.juku2024.juku.adapter.DlRunningAdapter
import com.juku2024.juku.base.BaseActivity
import com.juku2024.juku.base.BaseFragment
import com.juku2024.juku.callback.OnNoDoubleClickListener
import com.juku2024.juku.dialog.CommonDialog
import com.juku2024.juku.model.DownloadActionModel
import com.juku2024.juku.tools.*
import com.juku2024.juku.viewmodel.DownloadViewModel
import com.juku2024.juku.widget.LoadingView
import com.wanban.download.WBDownloadUtils
import com.wanban.download.db.DownloadEntity
import com.wanban.download.model.Status
import io.reactivex.disposables.Disposable
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class DownloadingFragment : BaseFragment() {

    private var disposable: Disposable? = null
    private val deleteList by lazy { ArrayList<DownloadEntity>() }
    private val runningAdapter by lazy { DlRunningAdapter(ArrayList()) }
    private val viewModel by lazy { getViewModel(DownloadViewModel::class.java) }
    private var deleteDialog: CommonDialog? = null

    private lateinit var btnAll: Button
    private lateinit var btnDelete: Button
    private lateinit var recyclerRunning: RecyclerView
    private lateinit var loadingView: LoadingView
    private lateinit var editLayout: View

    override fun layoutView(inflater: LayoutInflater, container: ViewGroup?): View {
        return inflater.inflate(R.layout.fragment_downloading, container, false)
    }

    override fun initView(rootView: View) {
        super.initView(rootView)
        btnAll = rootView.findViewById(R.id.btnAll_downloading)
        btnDelete = rootView.findViewById(R.id.btnDelete_downloading)
        recyclerRunning = rootView.findViewById(R.id.recyclerRunning)
        loadingView = rootView.findViewById(R.id.loadingView_downloading)
        editLayout = rootView.findViewById(R.id.editLayout_downloading)


        val layoutManager = WrapLinearLayoutManager(requireContext())
        recyclerRunning.layoutManager = layoutManager
        recyclerRunning.adapter = runningAdapter
        recyclerRunning.itemAnimator = null
    }

    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
    }

    override fun onResume() {
        super.onResume()
        getDownloadingList()
    }

    override fun bindEvent() {
        runningAdapter.setOnItemClickListener { _, _, position ->
            val item = runningAdapter.data[position]
            if (runningAdapter.isShowCheck) {
                item.isSelected = !item.isSelected
                runningAdapter.notifyItemChanged(position)
                modifySelectNum()
            } else {
                if (NetworkUtils.isNetworkTypeMobile() && WBDownloadUtils.isDownloadOnlyWifi()) {
                    showMobileWarningDialog()
                    return@setOnItemClickListener
                }

                // 非出错状态，该如何如何
                if (item.state == Status.START || item.state == Status.DOWNLOADING) { // 正在下载
//                MultiDownloadManager.stopDownload(item.url)
                    WBDownloadUtils.stopDownload(item.url)
                } else {
                    WBDownloadUtils.resumeDownload(item.url)
//                MultiDownloadManager.resumeDownload(item.url)
                }
            }
        }

        btnAll.setOnClickListener {
            val count = runningAdapter.data.count { it.isSelected }
            if (count == runningAdapter.data.size) {
                runningAdapter.data.forEach { it.isSelected = false }
            } else {
                runningAdapter.data.forEach { it.isSelected = true }
            }
            runningAdapter.notifyDataSetChanged()
            modifySelectNum()
        }

        btnDelete.setOnClickListener {
            if (isFragmentNotActive() || runningAdapter.data.isEmpty()) return@setOnClickListener
            val deleteListTemp = runningAdapter.data.filter { it.isSelected }
            if (deleteListTemp.isEmpty()) return@setOnClickListener
            deleteList.clear()
            deleteList.addAll(deleteListTemp)

            if (deleteDialog == null) {
                deleteDialog = CommonDialog(requireActivity())
            }
            deleteDialog?.showDialog(
                "您确认删除选中的缓存内容吗？",
                getString(R.string.confirm), {
                    // 查询要删除的选项
                    WBDownloadUtils.deleteDownloads(deleteList) {
                        // 当前页面的cache删除数据
                        deleteList.forEach { runningAdapter.remove(it) }
                        modifySelectNum()
                        if (runningAdapter.data.isEmpty()) {
                            // 全部清空了，需要重置状态
                            updateEditUI()
                            loadingView.showEmptyStatus(getString(R.string.dl_no_download))
                            (requireActivity() as DownloadDetailActivity).resetEditStatus()
                        }
                    }


                    deleteDialog?.dismiss()
                }, getString(R.string.cancel), {
                    deleteDialog?.dismiss()
                }
            )
            deleteDialog?.show()
        }
    }


    private fun getDownloadingList() {
        loadingView.showLoading()
        viewModel.getDownloadingData({
            if (isFragmentNotActive()) return@getDownloadingData
            loadingView.hideLoading()
            if (it.isEmpty()) {
                loadingView.showEmptyStatus(getString(R.string.dl_no_download))
                return@getDownloadingData
            }
//            runningAdapter.setList(it.sortedBy { it.episodeIndex }.sortedBy { it.videoId })
            runningAdapter.setList(it.sortedBy { it.createTime })
        }, {
            if (isFragmentNotActive()) return@getDownloadingData
            loadingView.hideLoading()
            loadingView.showEmptyStatus(getString(R.string.dl_no_download))
        })
    }



    /**
     * 新下载
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onNewDownloadEvent(event: DownloadEntity) {
        if (isFragmentNotActive()) return
        val index = runningAdapter.data.indexOfFirst { it.url == event.url }
        if (index == -1) return
        val target = runningAdapter.data[index]
        when (event.state) {
            Status.SUCCESS -> {
                runningAdapter.remove(target)
                if (runningAdapter.data.isEmpty()) {
                    loadingView.showEmptyStatus(getString(R.string.dl_no_download))
                }
            }
            else -> {
                target.state = event.state
                target.contentLength = event.contentLength
                target.speed = event.speed
                target.errorMsg = event.errorMsg
                target.percent = event.percent
                runningAdapter.notifyItemChanged(index)
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onDownloadAction(actionModel: DownloadActionModel) {
        if (actionModel.currentItem != 0) return
        if (runningAdapter.data.isEmpty()) return
        // 更改编辑按钮的状态
        (requireActivity() as DownloadDetailActivity).changeEditStatus()
        changeEditUI(actionModel.isShowEditStatus)
    }

    override fun onStop() {
        super.onStop()
        deleteDialog?.dismiss()
    }

    private fun changeEditUI(isShowEditUI: Boolean){
        runningAdapter.isShowCheck = isShowEditUI
        runningAdapter.data.forEach { it.isSelected = false }
        runningAdapter.notifyDataSetChanged()
        btnDelete.setTextColor(AppUtils.getColor(R.color.color_text_dark))
        btnDelete.text = String.format(AppUtils.getString(R.string.delete))
        btnAll.text = getString(R.string.select_all)
        editLayout.visibility = if (isShowEditUI) { View.VISIBLE } else { View.GONE }
    }


    private fun showMobileWarningDialog() {
        val activity = requireActivity() as BaseActivity
        activity.showErrorDialog(
            AppUtils.getString(R.string.phone_download_tips),
            AppUtils.getString(R.string.forward), object : OnNoDoubleClickListener {
                override fun onNoDoubleClick(v: View?) {
                    super.onNoDoubleClick(v)
                    activity.hideErrorDialog()
                    val intent = Intent(requireContext(), SettingActivity::class.java)
                    startActivity(intent)
                }

            }, AppUtils.getString(R.string.cancel), object : OnNoDoubleClickListener {
                override fun onNoDoubleClick(v: View?) {
                    super.onNoDoubleClick(v)
                    activity.hideErrorDialog()
                }
            }
        )
    }

    private fun modifySelectNum() {
        if (runningAdapter.data.isEmpty()) {
            return
        }
        val count = runningAdapter.data.count { it.isSelected }
        if (count != 0) {
            val text = if (count >= runningAdapter.data.size) {
                getString(R.string.cancel_select_all)
            } else {
                getString(R.string.select_all)
            }
            btnAll.text = text
            btnDelete.setTextColor(AppUtils.getColor(R.color.color_text_light))
            btnDelete.text = String.format(AppUtils.getString(R.string.delete_num), count)
        } else {
            btnDelete.setTextColor(AppUtils.getColor(R.color.color_text_dark))
            btnDelete.text = String.format(AppUtils.getString(R.string.delete))
            btnAll.text = getString(R.string.select_all)
        }
    }

    private fun updateEditUI() {
        runningAdapter.isShowCheck = !runningAdapter.isShowCheck
        if (runningAdapter.isShowCheck) {
            editLayout.visibility = View.VISIBLE
        } else {
            editLayout.visibility = View.GONE
        }
        runningAdapter.notifyDataSetChanged()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        disposable?.dispose()
    }



}